package com.along.dev.rbac.service;

import com.along.dev.rbac.dto.DeptDTO;
import com.along.dev.rbac.dto.MenuDTO;
import com.along.dev.rbac.entity.Menu;
import com.along.dev.rbac.mapper.MenuMapper;
import com.along.dev.rbac.qo.DeptQO;
import com.along.dev.rbac.qo.MenuQO;
import com.along.utility.common.utils.BeanUtils;
import com.along.utility.common.utils.JsonUtils;
import com.along.utility.common.utils.ListCopier;
import com.along.utility.page.mybatis.Paging;
import com.github.pagehelper.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/*
 * @Author: liujinyi
 * @DateTime: 2025/9/15 17:41
 */
@Service
public class MenuService {

    @Autowired
    private MenuMapper menuMapper;

    private static final Logger logger = LoggerFactory.getLogger(MenuService.class);

    public List<Menu> getMenuTree() {
        List<Menu> allMenus = menuMapper.findAllVisibleMenus();
        return buildMenuTree(allMenus, 0L);
    }

    @Paging
    public Page<MenuDTO> find(MenuQO menuQO, Integer page, Integer rows) {
        return ListCopier.pageCopy(this.menuMapper.find(menuQO), MenuDTO.class);
    }

    @Transactional(rollbackFor = Exception.class)
    public void save(MenuDTO menuDTO) {
        Date date = new Date();
        menuDTO.setCreateTime(date);
        menuDTO.setUpdateTime(date);
        Menu menu = BeanUtils.copy(menuDTO, new Menu());
        int size = menuMapper.save(menu);
        logger.info("保存菜单信息: {}, result: {}", JsonUtils.write(menuDTO), size);
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(MenuDTO menuDTO) {
        menuDTO.setUpdateTime(new Date());
        Menu menu = BeanUtils.copy(menuDTO, new Menu());
        int size = menuMapper.update(menu);
        logger.info("修改菜单信息: {}, result: {}", JsonUtils.write(menuDTO), size);
    }

    public void delete(MenuDTO menuDTO) {
        int result = menuMapper.delete(menuDTO.getMenuId());
        logger.info("删除菜单信息：menuId: {}, result: {}", JsonUtils.write(menuDTO.getMenuId()), result);
    }

    public void updateStatus(MenuDTO menuDTO) {
        int result = menuMapper.updateStatus(menuDTO.getMenuId(), menuDTO.getStatus());
        logger.info("更新菜单状态：menuId: {}, status: {}, result: {}",
                menuDTO.getMenuId(), menuDTO.getStatus(), result);
    }

    private List<Menu> buildMenuTree(List<Menu> menus, Long parentId) {
        return menus.stream()
                .filter(menu -> menu.getParentId().equals(parentId))
                .peek(menu -> menu.setChildren(buildMenuTree(menus, menu.getMenuId())))
                .collect(Collectors.toList());
    }
}
